package com.cs342.uwosh.cloudycontacts;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import com.cs342.uwosh.cloudycontacts.tasks.db.CreateCategoryTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.GetAllContactTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.GetCategoryByIdTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.UpdateCategoryTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.UpdateContactTask;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;


public class CreateEditCategoryActivity extends PreferenceActivity {

	EditText nameOfCategory;
	String catName;
	
	static Context mainContext;
	public static final int[] DEFAULT_THEME_ARRAY = 
			new int[] 
					{
					R.color.background_color_theme_default,
					R.color.category_btn_color_theme_default,
					R.color.list_item_color_theme_default,
					R.layout.custom_checkbox_theme_default,
					R.color.button_color_theme_default,
					R.style.ButtonText_theme_default,
					R.style.ButtonText_theme_default,
					R.style.ListItemText_theme_default,
					R.style.EditText_theme_default,
					R.color.category_btn_color_theme_default_pressed
					};
	
	public static final int[] ONE_THEME_ARRAY =
			new int[] 
					{
					R.color.background_color_theme_one,
					R.color.category_btn_color_theme_one,
					R.color.list_item_color_theme_one,
					R.layout.custom_checkbox_theme1_default,
					R.color.button_color_theme_one,
					R.style.ButtonText_theme1_default,
					R.style.ButtonText_theme1_default,
					R.style.ListItemText_theme1_default,
					R.style.EditText_theme1_default,
					R.color.category_btn_color_theme_one_pressed
					};
	
	public static final int[] TWO_THEME_ARRAY =
			new int[] 
					{
					R.color.background_color_theme_two,
					R.color.category_btn_color_theme_two,
					R.color.list_item_color_theme_two,
					R.layout.custom_checkbox_theme2_default,
					R.color.button_color_theme_two,
					R.style.ButtonText_theme2_default,
					R.style.ButtonText_theme2_default,
					R.style.ListItemText_theme2_default,
					R.style.EditText_theme2_default,
					R.color.category_btn_color_theme_two_pressed
					};
	
	public static final int[] THREE_THEME_ARRAY =
			new int[] 
					{
					R.color.background_color_theme_three,
					R.color.category_btn_color_theme_three,
					R.color.list_item_color_theme_three,
					R.layout.custom_checkbox_theme3_default,
					R.color.button_color_theme_three,
					R.style.ButtonText_theme3_default,
					R.style.ButtonText_theme3_default,
					R.style.ListItemText_theme3_default,
					R.style.EditText_theme3_default,
					R.color.category_btn_color_theme_three_pressed
					};
	
	
	public static String THEME_DEFAULT = "DEFAULT";

	public static String THEME_ONE = "THEME_ONE";

	public static String THEME_TWO = "THEME_TWO";

	public static String THEME_THREE = "THEME_THREE";

	public static String CURRENT_THEME = THEME_DEFAULT;

	
	int categoryId;
	PreferenceScreen target;
	ArrayList<Contact> contactsInCategory = new ArrayList<Contact>();
	SharedPreferences[] perfs;
	Category currentCategory;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	
		addPreferencesFromResource(R.xml.category_contact_pref);
		setContentView(R.layout.activity_create_edit_category);
		mainContext = this;
		
		
		Intent intent = getIntent();
		String categoryNumber = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
		categoryId = Integer.parseInt(categoryNumber);

		try {
			contactsInCategory = new GetAllContactTask().execute().get();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}

        target = (PreferenceScreen)findPreference("checkbox_pref");
        

		nameOfCategory = (EditText) findViewById(R.id.categoryNameEditText);
		
		if(!this.categoryExists(Integer.parseInt(categoryNumber))) // editing a category
		{
			currentCategory = new Category("Category " + categoryNumber);
		}
		else
		{
			try {
				currentCategory = new GetCategoryByIdTask().execute(null,categoryId,currentCategory).get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
		nameOfCategory.setText(currentCategory.getCategoryName());
	}
	

	
	
	/*
	 * Breakdown of indexing of the themes arrays
	 * [0] = App background color
	 * [1] = TextView category buttons at the top of MainActivity
	 * [2] = List items for main list of contacts
	 * [3] = CheckBoxPreferences on the Create/Edit categories activity
	 * [4] = All of the apps actual buttons
	 * [5] = Category "buttons" text
	 * [6] = All actual buttons text
	 * [7] = ListView text
	 * [8] = EditText text
	 */
	private void applyTheme(int[] themeToApply)
	{
		findViewById(R.id.createEditCatMainLinLayout).setBackgroundResource(themeToApply[0]);
		findViewById(R.id.create_edit_category_cancel).setBackgroundResource(themeToApply[4]);
		findViewById(R.id.create_edit_category_save).setBackgroundResource(themeToApply[4]);
		TextView cancelBtn = (TextView) findViewById(R.id.create_edit_category_cancel);
		cancelBtn.setTextAppearance(this, themeToApply[6]);
		TextView saveBtn = (TextView) findViewById(R.id.create_edit_category_save);
		saveBtn.setTextAppearance(this, themeToApply[6]);
		TextView catName = (TextView) findViewById(R.id.categoryNameEditText);
		catName.setTextAppearance(this, themeToApply[8]);
	}
	
	
	private void runChecks()
	{
		try {
			contactsInCategory = new GetAllContactTask().execute().get();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		}

        target = (PreferenceScreen)findPreference("checkbox_pref");
        
		for(Contact contact: contactsInCategory)
		{
			if(contact.getCategoryID() == categoryId)
			{
				CheckBoxPreference temp = (CheckBoxPreference) target.findPreference(""+contact.getId());
	        	temp.setChecked(true);		
			}
			else
			{
				CheckBoxPreference temp = (CheckBoxPreference) target.findPreference(""+contact.getId());
	        	temp.setChecked(false);	
			}
		}	
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		
		if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_DEFAULT))
        {
			applyTheme(MainActivity.DEFAULT_THEME_ARRAY);
        }
        else if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_ONE))
        {
        	applyTheme(MainActivity.ONE_THEME_ARRAY);
        }
        else if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_TWO))
        {
        	applyTheme(MainActivity.TWO_THEME_ARRAY);
        }
        else if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_THREE))
        {
        	applyTheme(MainActivity.THREE_THEME_ARRAY);
        }
		
		
		
		
		
		target.removeAll();
		for(int i = 0; i < contactsInCategory.size(); i++)
		{
			CheckBoxPreference checkBoxPreference = new CheckBoxPreference(this);
	        
	        checkBoxPreference.setTitle(""+contactsInCategory.get(i).getName());
	        checkBoxPreference.setKey(""+ contactsInCategory.get(i).getId());
	        
	        if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_DEFAULT))
	        {
	        	checkBoxPreference.setLayoutResource(R.layout.custom_checkbox_theme_default);
	        }
	        else if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_ONE))
	        {
	        	//checkBoxPreference.setLayoutResource(R.layout.custom_checkbox_theme1_default);
	        }
	        else if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_TWO))
	        {
	        	//checkBoxPreference.setLayoutResource(R.layout.custom_checkbox_theme2_default);
	        }
	        else if (MainActivity.CURRENT_THEME.equals(MainActivity.THEME_THREE))
	        {
	        	//checkBoxPreference.setLayoutResource(R.layout.custom_checkbox_theme3_default);
	        }
	        
	        if(contactsInCategory.get(i).getCategoryID() == categoryId)
	        {
	        	 checkBoxPreference.setChecked(true);
	        }
	        else
	        {
	        	 checkBoxPreference.setChecked(false);
	        }

	        target.addPreference(checkBoxPreference);
	        target.setWidgetLayoutResource(R.layout.custom_checkbox_theme_default);
	        
		}
		
		runChecks();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_create_edit_category, menu);
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.themes:
			generateThemesDialog();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	private   void generateThemesDialog()
	{
		final CharSequence[] themesList = new CharSequence[] 
				{
				THEME_DEFAULT,
				THEME_ONE,
				THEME_TWO,
				THEME_THREE
				};
		AlertDialog.Builder themesDialog = new AlertDialog.Builder(this);
		
		themesDialog.setTitle("Choose Your Theme");
		
		themesDialog.setSingleChoiceItems(themesList, -1, new DialogInterface.OnClickListener()
		{
			
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				if (themesList[which].equals(THEME_DEFAULT))
				{
					MainActivity.CURRENT_THEME = MainActivity.THEME_DEFAULT;
					applyTheme(DEFAULT_THEME_ARRAY);
					new GetAllContactTask().execute();
					dialog.cancel();
				}
				else if (themesList[which].equals(THEME_ONE))
				{
					MainActivity.CURRENT_THEME = MainActivity.THEME_ONE;
					applyTheme(ONE_THEME_ARRAY);
					new GetAllContactTask().execute();
					dialog.cancel();
				}
				else if (themesList[which].equals(THEME_TWO))
				{
					MainActivity.CURRENT_THEME = MainActivity.THEME_TWO;
					applyTheme(TWO_THEME_ARRAY);
					new GetAllContactTask().execute();
					dialog.cancel();
				}
				else if (themesList[which].equals(THEME_THREE))
				{
					MainActivity.CURRENT_THEME = MainActivity.THEME_THREE;
					applyTheme(THREE_THEME_ARRAY);
					new GetAllContactTask().execute();
					dialog.cancel();
				}
				
			}
		});
		themesDialog.show();
	}
		
	
	public void cancel(View view)
	{				
		this.finish();
	}
	
	public void saveCategory(View view)
	{
		
        SharedPreferences myPref= PreferenceManager.getDefaultSharedPreferences(this);

		for(Contact contact: contactsInCategory)
		{
	        boolean inCat = myPref.getBoolean(""+contact.getId(), false);
	        
	        if(inCat)
	        {
	        	contact.setCategoryID(categoryId);
	        	new UpdateContactTask().execute(contact);
	        }
	        else
	        {
	        	if(categoryId < MainActivity.db.categoryCount() && contact.getCategoryID() == categoryId)
	        	{
		        	contact.setCategoryID(0);
		        	new UpdateContactTask().execute(contact);
	        	}
	        }
	        CheckBoxPreference temp = (CheckBoxPreference) target.findPreference(""+contact.getId());
	        temp.setChecked(false);
			MainActivity.categoryViewed = categoryId;
		}
		
		if(!this.categoryExists(categoryId)) // editing a category
		{
			currentCategory.setCatagoryName(nameOfCategory.getText().toString());
			int catNumber = MainActivity.db.categoryCount()+1;
			currentCategory.setCid(catNumber);
			currentCategory.setTS(""+System.currentTimeMillis());
			new CreateCategoryTask().execute(currentCategory);
		}
		else
		{
			currentCategory.setCatagoryName(nameOfCategory.getText().toString());
			currentCategory.setTS(""+System.currentTimeMillis());
			new UpdateCategoryTask().execute(currentCategory);
		}
		
		MainActivity.categoryViewed = this.categoryId;

		this.finish();
	}
	
	/**
	 * Used to determine whether a new category must be created, or if 
	 * a category is being edited.
	 * @param numberPassedToActivity The number passed into this class after a click 
	 * to create a new category, or a long click to edit a category.
	 * @return True if the numberPassedToActivity is not greater than the row count for the categories table.
	 */
	public boolean categoryExists(int numberPassedToActivity)
	{
		if(numberPassedToActivity > MainActivity.db.categoryCount())
		{
			return false;
		}
		else
		{
			return true;
		}
	}
		
}